<template>
  <div class="login-container">
    <div class="login-box">
      <div class="login-title">欢迎注册</div>
      <div class="login-subtitle">团队小助手</div>
      
      <el-form :model="data.form" ref="formRef" :rules="data.rules" class="login-form">
        <el-form-item prop="username">
          <el-input 
            :prefix-icon="User" 
            size="large" 
            v-model="data.form.username" 
            placeholder="请输入用户名" 
            class="custom-input"
          />
        </el-form-item>
        <el-form-item prop="phone">
          <el-input 
            :prefix-icon="User" 
            size="large" 
            v-model="data.form.phone" 
            placeholder="请输入手机号" 
            class="custom-input"
          />
        </el-form-item>
        <el-form-item prop="password">
          <el-input 
            :prefix-icon="Lock" 
            size="large" 
            v-model="data.form.password" 
            placeholder="请输入密码" 
            show-password 
            class="custom-input"
          />
        </el-form-item>
        <el-form-item prop="confirmPassword">
          <el-input 
            :prefix-icon="Lock" 
            size="large" 
            v-model="data.form.confirmPassword" 
            placeholder="请确认密码" 
            show-password 
            class="custom-input"
          />
        </el-form-item>
        <el-form-item>
          <el-button size="large" type="primary" class="login-button" @click="register">注 册</el-button>
        </el-form-item>
      </el-form>
      
      <div class="register-link">
        已有账号？请 <router-link to="/login" class="link-text">登录</router-link>
      </div>
    </div>
  </div>
</template>

<script setup>
import { reactive, ref } from "vue";
import { User, Lock } from "@element-plus/icons-vue";
import request from "@/utils/request";
import {ElMessage} from "element-plus";
import router from "@/router";

const data = reactive({
  form: {
    username: '',
    phone: '',
    password: '',
    confirmPassword: ''
  },
  rules: {
    username: [
      { required: true, message: '请输入用户名', trigger: 'blur' },
      { min: 2, max: 20, message: '用户名长度2-20位', trigger: 'blur' }
    ],
    phone: [
      { required: true, message: '请输入手机号', trigger: 'blur' },
      { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
    ],
    password: [
      { required: true, message: '请输入密码', trigger: 'blur' },
      { min: 6, max: 20, message: '密码长度6-20位', trigger: 'blur' },
      {
        validator: (rule, value, callback) => {
          const hasLetter = /[a-zA-Z]/.test(value);
          const hasNumber = /\d/.test(value);
          const hasSpecialChar = /[^a-zA-Z0-9]/.test(value);
          
          if ((hasLetter && hasNumber) || 
              (hasLetter && hasSpecialChar) || 
              (hasNumber && hasSpecialChar)) {
            callback();
          } else {
            callback(new Error('密码必须包含字母、数字或特殊字符中的至少两种'));
          }
        },
        trigger: 'blur'
      }
    ],
    confirmPassword: [
      { required: true, message: '请确认密码', trigger: 'blur' },
      {
        validator: (rule, value, callback) => {
          if (value !== data.form.password) {
            callback(new Error('两次输入密码不一致'))
          } else {
            callback()
          }
        },
        trigger: 'blur'
      }
    ]
  }
})

const formRef = ref()

const register = () => {
    formRef.value.validate((valid => {
        if (valid) {
            // 显示加载状态
            const loading = ElMessage({
                message: '注册中...',
                type: 'info',
                duration: 0,
                showClose: false
            });
            
            // 修正接口路径
            request.post('/api/auth/register', data.form)
                .then(res => {
                    loading.close();
                    
                    if (res.code === '200' || res.code === 200) {
                        ElMessage.success("注册成功");
                        router.push('/login');
                    } else {
                        // 处理业务逻辑错误
                        const errorMsg = res.msg || res.message || '注册失败，请重试';
                        ElMessage.error(errorMsg);
                    }
                })
                .catch(error => {
                    loading.close();
                    
                    // 处理网络和服务器错误
                    let errorMessage = '注册失败，请重试';
                    
                    if (error.response) {
                        // 服务器返回了错误状态码
                        const status = error.response.status;
                        const data = error.response.data;
                        
                        switch (status) {
                            case 400:
                                errorMessage = data?.msg || data?.message || '请求参数错误';
                                break;
                            case 409:
                                errorMessage = data?.msg || data?.message || '用户名或手机号已存在';
                                break;
                            case 422:
                                errorMessage = data?.msg || data?.message || '数据验证失败';
                                break;
                            case 500:
                                errorMessage = '服务器内部错误，请稍后重试';
                                break;
                            case 503:
                                errorMessage = '服务暂时不可用，请稍后重试';
                                break;
                            default:
                                errorMessage = data?.msg || data?.message || `服务器错误 (${status})`;
                        }
                    } else if (error.request) {
                        // 网络错误
                        if (error.code === 'ECONNABORTED') {
                            errorMessage = '请求超时，请检查网络连接';
                        } else {
                            errorMessage = '网络连接失败，请检查网络设置';
                        }
                    } else {
                        // 其他错误
                        errorMessage = error.message || '未知错误，请重试';
                    }
                    
                    ElMessage.error(errorMessage);
                    console.info('注册信息:', {
                        message: errorMessage,
                        timestamp: new Date().toLocaleString(),
                        type: 'register_error'
                    });
                });
        }
    }));
};
</script>

<style scoped>
.login-container {
  height: 100vh;
  overflow: hidden;
  display: flex;
  justify-content: center;
  align-items: center;
  background: linear-gradient(135deg, #a8c0ff, #6e8eff, #3f2b96);
  background-size: 400% 400%;
  animation: gradient 15s ease infinite;
}

@keyframes gradient {
  0% { background-position: 0% 50%; }
  50% { background-position: 100% 50%; }
  100% { background-position: 0% 50%; }
}

.login-box {
  width: 380px;
  padding: 40px 35px;
  border-radius: 12px;
  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.15);
  background-color: rgba(255, 255, 255, 0.85);
  backdrop-filter: blur(10px);
  transition: all 0.3s ease;
  transform: translateY(0);
}

.login-box:hover {
  transform: translateY(-5px);
  box-shadow: 0 15px 30px rgba(0, 0, 0, 0.2);
}

.login-title {
  font-weight: bold;
  font-size: 28px;
  text-align: center;
  margin-bottom: 8px;
  color: #1450aa;
  letter-spacing: 2px;
}

.login-subtitle {
  font-size: 16px;
  text-align: center;
  margin-bottom: 30px;
  color: #666;
  letter-spacing: 1px;
}

.login-form {
  margin-bottom: 20px;
}

.custom-input :deep(.el-input__wrapper) {
  box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.1) inset;
  border-radius: 8px;
  padding: 0 15px;
  transition: all 0.3s;
}

.custom-input :deep(.el-input__wrapper:hover) {
  box-shadow: 0 0 0 1px #1967e3 inset;
}

.custom-input :deep(.el-input__wrapper.is-focus) {
  box-shadow: 0 0 0 1px #1967e3 inset;
}

.login-button {
  width: 100%;
  border-radius: 8px;
  background: linear-gradient(90deg, #1450aa, #1967e3);
  border: none;
  font-weight: 500;
  letter-spacing: 2px;
  transition: all 0.3s;
  height: 44px;
}

.login-button:hover {
  background: linear-gradient(90deg, #1967e3, #1450aa);
  transform: translateY(-2px);
  box-shadow: 0 5px 15px rgba(25, 103, 227, 0.3);
}

.register-link {
  text-align: right;
  font-size: 14px;
  color: #666;
  margin-top: 15px;
}

.link-text {
  color: #1967e3;
  text-decoration: none;
  font-weight: 500;
  transition: all 0.3s;
}

.link-text:hover {
  color: #1450aa;
  text-decoration: underline;
}
</style>
ElMessage.success("注册成功")